package per.dg.multiprocesskotlin.aidl

import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.View
import per.dg.multiprocesskotlin.R
import per.dg.multiprocesskotlin.messenger.MessengerService

class AIDLClientActivity : AppCompatActivity() {

    private val TAG = "AIDLClientActivity"

    private var mIServiceInterface : IServiceInterface? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_a_i_d_l_client)
    }

    fun onClick(view: View) {
        when (view.id){
            R.id.bt_connection_service ->{
                if(mIServiceInterface == null){
                    startAndBindService()
                }else{
                    Log.e(TAG, "onClick: 服务已启动" )
                    Log.e(TAG, "onClick: ${mIServiceInterface!!.getUser(User())}" )
                }
            }
            R.id.bt_call_method_getuser ->{
                var user = mIServiceInterface!!.getUser(User())
                Log.e(TAG, "onClick: ${user?.name}" )
            }
        }

    }

    fun startAndBindService(){
        //        启动服务
        startService(Intent(this, AIDLService::class.java))
        //        绑定服务
        bindService(Intent(this, AIDLService::class.java), mServiceConnection, Service.BIND_AUTO_CREATE)
    }

    val mServiceConnection : ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {
            mIServiceInterface = null
        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            mIServiceInterface = IServiceInterface.Stub.asInterface(service)
            if(mIServiceInterface != null){
                mIServiceInterface!!.registerCallBack(mIClientInterfaceStub)
            }
        }
    }

    val mIClientInterfaceStub = object : IClientInterface.Stub() {
        override fun notice() {
            Log.e(TAG, "notice: " )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(mIServiceInterface != null){
            mIServiceInterface!!.unRegisterCallBack(mIClientInterfaceStub)
            unbindService(mServiceConnection)
        }
    }
}